/*
 * description：API接口请求包装方法
 * author：King Feng
 * Date: 2017年1月24日09:45:44
 */
var API = {
    /**
     * GET请求，异步，不能设置requestHeader
     * @param url              请求服务器url地址
     * @param requestBod      请求体参数,json格式,例：{'name':'zhang','password':'123456'}
     * @param successCallback 成功回调
     * @param errorCallback   失败回调
     */
    get: function (url, param, successCallback, errorCallback) {
        //ajax(async,requestMethod,requestUrl,requestBody,successCallback,errorCallback)
        API.ajax(true, 'GET', url, param, successCallback, errorCallback);
        /*if(url == null || url == ""){
         return;
         }
         var requestType = 'GET';
         var auth = API.AES(requestType,url);
         var header = {
         "App-Access-Id":1000,
         "Authorization":auth,
         "Access-Control-Allow-Origin":"http://web.arkisv.com"
         }
         if(param == null || param == ""){
         param = {};
         }
         var settings = {
         type		: requestType,
         async		: true, 	//同步请求,默认为true异步
         url			: url,
         dataType	: "json",
         headers		: header,
         data		: param,
         success		: function(data,textStatus) {
         if(successCallback != undefined)
         successCallback(data,textStatus);
         },
         error		: function(XMLHttpRequest, textStatus, errorThrown) {
         if(errorCallback != undefined)
         errorCallback(XMLHttpRequest, textStatus, errorThrown);
         }
         };
         // 发送ajax请求
         $.ajax(settings);*/
    },
    /**
     * GET请求，异步，不能设置requestHeader
     * @param url              请求服务器url地址
     * @param requestBod      请求体参数,json格式,例：{'name':'zhang','password':'123456'}
     * @param successCallback 成功回调
     * @param errorCallback   失败回调
     */
    post: function (url, param, successCallback, errorCallback) {
        API.ajax(true, 'POST', url, param, successCallback, errorCallback);
    },
    /**
     * GET请求，异步，不能设置requestHeader
     * @param url              请求服务器url地址
     * @param requestBod      请求体参数,json格式,例：{'name':'zhang','password':'123456'}
     * @param successCallback 成功回调
     * @param errorCallback   失败回调
     */
    put: function (url, param, successCallback, errorCallback) {
        API.ajax(true, 'PUT', url, param, successCallback, errorCallback);
    },
    /**
     * GET请求，异步，不能设置requestHeader
     * @param url              请求服务器url地址
     * @param requestBod      请求体参数,json格式,例：{'name':'zhang','password':'123456'}
     * @param successCallback 成功回调
     * @param errorCallback   失败回调
     */
    delete: function (url, param, successCallback, errorCallback) {
        API.ajax(true, 'DELETE', url, param, successCallback, errorCallback);
    },
    /**
     * 加密方法
     * @param requestType     请求类型
     * @param requestUrl      请求路径，ex：/api/v1/test/mail
     */
    AES: function (requestType, requestUrl) {
        // localStorage.TOKEN='xxxxxxxxxx';
        var TOKEN = localStorage.TOKEN;
        var timestamp = new Date().getTime();
        var data = TOKEN + timestamp + requestType + requestUrl;
        var KEY = '41422321AC0A9849FDCA2904A750A45E';
        var keys = CryptoJS.enc.Utf8.parse(KEY);
        var iv = CryptoJS.enc.Utf8.parse(KEY.substring(16));
        var encrypted = CryptoJS.AES.encrypt(data, keys,
            {
                iv: iv,
                keySize: 256,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            });
        return encrypted.toString();
    },
    /**
     * <请勿直接调用!!!>
     * @description            IE浏览器发送数据,适用于IE7/8/9/10/11
     * @param requestType    请求服务器的方式(get/post),默认为get
     * @param requestUrl    请求服务器url地址
     * @param requestHeader    请求头参数,json格式
     * @param requestBody    请求体参数,json格式,例：{'name':'zhang','password':'123456'}
     * @param callback        回调函数
     * @param async            是异步?,默认异步(true:异步,false:同步)
     */
    ajax: function (async, requestMethod, requestUrl, requestBody, successCallback, errorCallback) {
        if (requestUrl == null || requestUrl == "") {
            return;
        }
//		var serverAddr = "http://192.168.10.210:8080";
//		var serverAddr = "http://192.168.10.133:8080";
        var serverAddr = $("#baseUrl").val();
        if (requestUrl == "/api/account/user/login") {
            serverAddr = "http://192.168.10.212";
        }
        var _async = true;
        // 除了async=false时为同步,其他都为异步
        if (!async) {
            _async = false;
        }
        if (requestMethod == null || requestMethod == "") {
            requestMethod = "GET";
        }

        var _method = requestMethod;
        // if(requestMethod == "PUT"){
        // 	_method = "POST";
        // 	requestBody._method="PUT";
        // }
        //       if (requestMethod == "DELETE") {
        //           _method = "POST";
        //           requestBody._method = "DELETE";
        //       }

        var auth = '';
        var index = requestUrl.indexOf("?");
        var murl = requestUrl;
        if (index > -1) {
            murl = requestUrl.substring(0, index);
        }
        if (localStorage.TOKEN != '' && localStorage.TOKEN != null) {
            auth = API.AES(requestMethod, murl);
        }

        var returnFileCheckbox = $("#returnFileCheckbox").is(':checked');
        if (returnFileCheckbox) {
            console.info("####auth = "+auth);
            this.downloadFile(requestMethod, auth, requestBody);
            return;
        }

        var requestHeader = {
            "App-Access-Id": 1000,
            "Authorization": auth,
            "Access-Control-Allow-Origin": "http://web.arkisv.com"
        }
        /*if(typeof requestBody == 'string'){
         requestBody = JSON.parse(requestBody);
         }*/
        if (requestBody == null || requestBody == "") {
            requestBody = {};
        }

        console.debug("==============================start========");
        console.debug(requestBody)
        console.debug("==============================end==========");
        var settings = {
            type: _method,
            async: _async, 	//同步请求,默认为true异步
            url: serverAddr + requestUrl,
            dataType: "json",
            headers: requestHeader,
            data: requestBody, //JSON.stringify(requestBody)
            contentType: "application/json",
            success: function (data, textStatus) {
                if (successCallback != undefined)
                    successCallback(data, textStatus);
            },
            error: function (xmlHttpRequest, textStatus, errorThrown) {
                if (errorCallback != undefined)
                    errorCallback(XMLHttpRequest, textStatus, errorThrown);

                $("#api_status").val(xmlHttpRequest.status);
            }
        };
        // 发送ajax请求
        $.ajax(settings);
    },
    downloadFile: function (requestMethod, authorization, dataParams) {
        //var as = $("#loadFileA");
        var url = $("#baseUrl").val() + $("#api_url").val() + '?App-Access-Id=1000&Authorization=' + authorization;
        for (var prop in dataParams) {//遍历json对象的每个key/value对,p为key
            var s = '&' + prop + '=' + dataParams[prop];
            url += s;
        }
        //window.location = encodeURI(url);
        window.location = encodeURI(url);
        //as.href = encodeURI(url);
        //as.click();

        /*var form = $("<form>");//定义一个form表单
         form.attr("style", "display:none");
         form.attr("target", "");
         form.attr("method", requestMethod);
         form.attr("action", $("#baseUrl").val() + $("#api_url").val());

         var auth = $("<input>");
         auth.attr("name","Authorization");
         auth.attr("value",authorization);
         form.append(auth);

         var app = $("<input>");
         app.attr("name","App-Access-Id");
         app.attr("value",1000);
         form.append(app);

         var pageNum = $("<input>");
         pageNum.attr("name","pageNum");
         pageNum.attr("value",1);
         form.append(pageNum);

         /!*for(var p in dataParams){//遍历json对象的每个key/value对,p为key
         var pi = $("<input>");
         pi.attr("name",p);
         pi.attr("value",dataParams[p]);
         form.append(pi);
         }*!/

         $("body").append(form);//将表单放置在web中
         form.submit().remove();//表单提交*/

        /*var exportExcel = "export_excel";
         dataParams[exportExcel] = 1;*/
        /*var params = $.param(dataParams);
         var url = $("#baseUrl").val() + $("#api_url").val() + "?Authorization="+authorization+'&App-Access-Id=1000&pageNum=1';
         $('<form method="'+requestMethod+'" action="' + url + '"></form>').appendTo('body').submit().remove();*/
        /*delete dataParams[exportExcel];*/
    }
}